package com.sunny.ynhz.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sunny.ynhz.R;


/**
 * Created by tangyunfei on 2016/12/11.
 */

public class IndicatorViewPager extends LinearLayout {
      private Paint mPaint;
      private Path mPath; //三角形路径
      private int mTriangleWidth; //三角形宽度
      private int mTriangleHeight;//三角形高度
      private final static  float TRIANGLE_WIDTH = 1/6F;//三角形底边
      private int mInitTranslationX;//控件开始的X位置
      private int mTranslationX;//移动的位置
      private int showTabCount;//显示tab数量
     private final  static  int COUNT_SHOW_TAB = 3;
     private String highlightColor; //高亮颜色
    private String normalColor;//正常的颜色

    public IndicatorViewPager(Context context) {
        this(context,null);
    }

    public IndicatorViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        //自定义属性
      TypedArray typedArray =  context.obtainStyledAttributes(attrs, R.styleable.IndicatorViewPager);
       showTabCount = typedArray.getInt(R.styleable.IndicatorViewPager_show_tab_count,COUNT_SHOW_TAB);
       highlightColor = typedArray.getString(R.styleable.IndicatorViewPager_highlight_color);
        normalColor = typedArray.getString(R.styleable.IndicatorViewPager_normal_color);
        if(showTabCount < 0){
            showTabCount = COUNT_SHOW_TAB;
        }
        if(highlightColor==null){
            highlightColor = "#DC2F2F";
        }
        if(normalColor == null){
            normalColor = "#000000";
        }
        typedArray.recycle();

        //初始化画笔
        mPaint = new Paint();
        mPaint.setColor(Color.parseColor(highlightColor));
        mPaint.setStyle(Paint.Style.FILL);

        mPaint.setAntiAlias(true);

    }

    //当View中所有的子控件均被映射成xml后触发
    @Override
    protected void onFinishInflate() {

        super.onFinishInflate();
        int count =getChildCount();
        if(count ==0){
            return;
        }else{
            for (int i=0;i<count;i++){
                View view = getChildAt(i);
                LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
                layoutParams.weight = 0;
                layoutParams.width = getDisplayWidth() / showTabCount; //设置内部每个textview的宽度
            }
        }
    }

    /**
     * 屏幕宽度
     * @return
     */
    private int getDisplayWidth(){
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;
        return width;
    }

    //当控件高宽发生变化
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mTriangleWidth = (int) (w/showTabCount * TRIANGLE_WIDTH);//三角形底边宽度  == 控件三分之一的6分之一
        mInitTranslationX = w/showTabCount/2 - mTriangleWidth /2; //控件开始的位置 在控件中间

        //初始化三角形
        initTriangle();
      // initCircular();

    }

    //初始化三角形图形
    private void initTriangle() {
        mTriangleHeight = mTriangleWidth /2;
        mPath = new Path();
        mPath.moveTo(0,0);
        mPath.lineTo(mTriangleWidth,0);
        mPath.lineTo(mTriangleWidth/2,-mTriangleHeight);
        mPath.close();
    }

    /**
     * 绘制圆形

     */
    private void initCircular(){
        mPath = new Path();
        mPath.addCircle(mTriangleWidth/2,-20,10, Path.Direction.CCW);
    }



    @Override
    protected void dispatchDraw(Canvas canvas) {
       canvas.save();
        canvas.translate(mInitTranslationX + mTranslationX,getHeight());
        canvas.drawPath(mPath,mPaint);
        canvas.restore();
        super.dispatchDraw(canvas);
    }

    //滑动事件
    public void scroll(int position, float offset) {
         int tabWidth = getWidth() / showTabCount;
         mTranslationX = (int) (tabWidth *(offset + position));
        if(position >= (showTabCount -1)&&offset >0&&getChildCount() >showTabCount){
            this.scrollTo((position - (showTabCount - 1)) * tabWidth + (int) (tabWidth * offset),0);
        }
        invalidate();
    }

    private ViewPager mVewPager;
    public void setViewPager(ViewPager viewPager,int pos){
       mVewPager = viewPager;
        mVewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

               scroll(position,positionOffset);

            }

            @Override
            public void onPageSelected(int position) {
                highlightTextView(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mVewPager.setCurrentItem(pos);
        highlightTextView(pos);
        setItemClick();
    }

    /**
     * 清楚文本颜色
     */
    private void clearTextViewColor(){
        for (int i=0;i<getChildCount();i++){
            View view = getChildAt(i);
            ((TextView)view).setTextColor(Color.parseColor(normalColor));
        }
    }

    /**
     * 设置选中textview高亮
     * @param pos
     */
    private void highlightTextView(int pos){
        clearTextViewColor();
        View view = getChildAt(pos);
        ((TextView)view).setTextColor(Color.parseColor(highlightColor));
    }

    /**
     * 设置tab点击事件
     */
    private void setItemClick(){
        int count = getChildCount();
        for (int i = 0;i<count;i++){
            final int pos = i;
            View view = getChildAt(i);
            ((TextView)view).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mVewPager.setCurrentItem(pos);
                }
            });
        }
    }

    /**
     * 设置tab数量
     * @param tabs
     */
    public void setTabItems(String[] tabs){
         if(tabs!=null&&tabs.length >0){
             removeAllViews();
             for(int i=0;i<tabs.length;i++){

                 addView(getTabView(tabs[i]));
             }
         }
    }

    private View getTabView(String name) {
        TextView tv = new TextView(getContext());
        LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        lp.width = getDisplayWidth() / showTabCount;
        tv.setText(name);
        tv.setGravity(Gravity.CENTER);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
        //tv.setTextColor(Color.parseColor("#cccccc"));
        tv.setLayoutParams(lp);
        return  tv;
    }


}
